<template>
  <div
    id="myChart"
    ref="chartDom"
    class="mt-4"
    style="width: 300px; height: 300px"
  />
</template>

<script setup lang="ts" name="LineChart">
import { getAqiIndexTrend } from "@/api/aqiMeasuredResult";
import { ref, onMounted, watch } from "vue";
import * as echarts from "echarts";
defineOptions({
  name: "LineChart"
});

const chartDom = ref(null);
const option = {
  title: {
    text: "12个月内空气质量超标趋势", // 将title设置为一个对象，包含text属性来设置标题文本
    left: "center", // 设置标题的位置
    textStyle: {
      color: "white"
    }
  },
  xAxis: {
    type: "category",
    axisLabel: {
      textStyle: {
        color: "white" // 修改x轴数据项的颜色
      },
      rotate: 45 // 控制文字的旋转角度
    },
    textAlign: "center", // 设置 x 轴刻度的对齐方式
    data: [] // 将 x 轴的数据设置为月份
  },
  yAxis: {
    type: "value",
    axisLabel: {
      textStyle: {
        color: "white" // 修改y轴文字颜色
      }
    }
  },
  series: [
    {
      data: [], // 将 series 的 data 设置为 count 值
      type: "line",
      smooth: true,
      lineStyle: {
        color: "CornflowerBlue" // 修改线条颜色
      }
    }
  ]
};

const monthData = ref([]);
const getAqiTrend = async () => {
  try {
    const { data } = await getAqiIndexTrend();
    monthData.value = data.map((item, index) => ({
      ...item,
      index: index + 1
    }));
    console.log(monthData.value);
  } catch (error) {
    console.log(error);
  }
};

onMounted(() => {
  const myChart = echarts.init(chartDom.value);
  option && myChart.setOption(option);
  getAqiTrend();
  // 使用 watch 函数监视 monthData 的变化
  watch(monthData, newVal => {
    if (newVal && newVal.length > 0) {
      option.xAxis.data = newVal.map(item => item.month);
      option.series[0].data = newVal.map(item => item.count);
      myChart.setOption(option);
    }
  });
});
</script>

<style></style>
